package com.info.controller;

import com.info.dal.UserDAL;
import com.info.model.UserInfo;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet(name = "loginServlet", value = "/loginServlet")
public class loginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //登录处理方法
        String username = request.getParameter("username");
        String userpass = request.getParameter("userpass");

        UserInfo userInfo = new UserInfo();
        userInfo.setUsername(username);
        userInfo.setUserpass(userpass);

        //System.out.println(username+","+userpass);
        //调用数据实现层里的登录验证方法
        UserDAL userDAL = new UserDAL();
        UserInfo user = userDAL.validateUserLogin(userInfo);

        if(user!=null){
            //登录成功
            HttpSession session = request.getSession();
            session.setAttribute("UserSession",user);
            System.out.println("登录成功");

            //权限判断
            if(user.getRolename().equals("管理员")){
                response.sendRedirect("admin/index.jsp");
            }else{
                //            request.getRequestDispatcher("user/index.jsp").forward(request,response);
                //页面重定向，推荐使用response.sendRedirect方法
                response.sendRedirect("user/index.jsp");
            }

        }else{
            System.out.println("登录失败");
            request.getRequestDispatcher("login.jsp").forward(request,response);
        }
    }


}
